﻿
using System;
using System.Collections.Generic;
using System.Linq;
using fc2editor.DataModel;
using fc2editor.Lua;
namespace fc2editor.Services
{
    public class WeaponService : IWeaponService
    {
        public WeaponService(IFileService fileService)
        {
            cache = LoadWeapons(fileService);
        }

        #region IWeaponService Members

        public Weapon[] GetWeapons()
        {
            return cache.Values.ToArray();
        }

        public Weapon GetWeaponByID(Guid id)
        {
            Weapon weapon = null;
            cache.TryGetValue(id, out weapon);
            return weapon;
        }

        #endregion

        private Dictionary<Guid, Weapon> LoadWeapons(IFileService fileService)
        {
            var parser = new WeaponParser();
            var weapons = parser.Parse(fileService.GetWeaponsFileName());
            LoadPictures(weapons, fileService);
            return weapons.ToDictionary(w => w.ID, w => w);
        }

        private void LoadPictures(IEnumerable<Weapon> weapons, IFileService fileService)
        {
            foreach (var w in weapons)
            {
                var pictureData = fileService.GetPicture(w);
                w.SetPictureData(pictureData);
            }
        }

        private Dictionary<Guid, Weapon> cache;
    }
}
